import selenium
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException, TimeoutException, ElementNotInteractableException, ElementClickInterceptedException
from time import sleep
import sys
import csv
from steam import login1

timeout = 40

with open('sub.csv') as f:
    r = csv.reader(f)
    accounts = list(r)

for account in accounts:
    print("[Process] " + account[2])
    br = webdriver.Firefox()
    br.set_page_load_timeout(timeout)
    br.set_script_timeout(timeout)
    wait = WebDriverWait(br, timeout)

    while True:
        try:
            login1(br, wait, account[2].strip(), account[3].strip())
            break
        except selenium.common.exceptions.TimeoutException:
            br.quit()
            br = webdriver.Firefox()
            br.set_page_load_timeout(timeout)
            br.set_script_timeout(timeout)
            wait = WebDriverWait(br, timeout)

    try:
        br.get("https://store.steampowered.com/gifts/")
    except selenium.common.exceptions.TimeoutException:
        print("timeout")

    try:
        btns = wait.until(EC.presence_of_all_elements_located(
            (By.CLASS_NAME, "btn_green_white_innerfade")))
    except TimeoutException:
        print('no btn found timeout')
        br.quit()
        continue

    for btn in btns:
        try:
            btn.click()
        except ElementClickInterceptedException:
            continue

        sleep(2)

        try:
            wait.until(EC.element_to_be_clickable(
                (By.CSS_SELECTOR, '[class="btn_green_white_innerfade btn_medium]'))).click()
        except TimeoutException:
            pass

        ll = br.find_elements_by_class_name("newmodal_buttons")
        for l in ll:
            try:
                l.find_element_by_class_name(
                    "btn_grey_white_innerfade").click()
            except ElementClickInterceptedException:
                pass

    br.quit()
